<?php
/**
 * Контроллер продуктов
 * 
 * Управление продуктов
 * @author Anton Zavidov
 * @package myLiveShop
 */

/**
 * Класс контроллера для управления продуктами
 *
 */
class ControllerProduct extends Element{
	/**
	 * Констуктор
	 *
	 * @param string $className имя контроллера
	 */
	public function __construct($className=null){
		$this->name='product';
		parent::__construct($className?$className:__CLASS__);
	}
	/**
	 * Просмотр елемента
	 *
	 */
	public function show($page=1){
		parent::show();
		import('model.product');
		import('model.image');
		$settings=array('where'=>ModelProduct::F_SHOP_ID.'='.Vars::_(Router::SHOP_ID));
		if($page!==false){
			$settings['pagination']=array(
				'page'=>$page,
				'show'=>true
			);
		}
		if(Requestlocal::getString('order')){
			$settings['order'] = Requestlocal::getString('order'); /// СДЕЛАТЬ более безопасной
		}
		$this->view->set(
			'list',
			$this->model()->load(
				false,
				array(
					ModelProduct::F_PRODUCT_ID,
					ModelProduct::F_TITLE,
					ModelProduct::F_DESCRIPTION,
					ModelProduct::F_PRICE,
					ModelImage::TABLE.DOT.ModelImage::F_FILENAME
				),
				$settings
			)
		);
		$this->view->set('pagination',$this->model()->pagination);
        $this->build();
	}
	/**
	 * Просмотр елемента
	 *
	 */
	public function display(){
		parent::display(true);
		import('model.category');
		$params = array();
		$fields = array(
		  ModelProduct::F_PRODUCT_ID,
		  ModelProduct::F_TITLE,
		  ModelProduct::F_DESCRIPTION,
		  ModelProduct::F_CATEGORY_ID,
		  ModelProduct::F_CREATED,
		  ModelProduct::F_PRICE,
		  ModelProduct::F_IMAGE_ID,
		  ModelProduct::F_SHOP_ID,
		  ModelCategory::TABLE.DOT.ModelCategory::F_TITLE,
		  ModelImage::TABLE.DOT.ModelImage::F_FILENAME
		);
		$cat=Requestlocal::getInt('category_id',null);
		if($cat != null){
			$params[] = ModelCategory::TABLE.DOT.ModelProduct::F_CATEGORY_ID."=".$cat;
		}
		$tag=Requestlocal::getInt('tag_id',null);
		if($tag != null){
			import('model.tag_to_product');
			$params[] .= ModelProduct::F_PRODUCT_ID." IN (SELECT ".ModelTag_to_product::TABLE.DOT.ModelTag_to_product::F_PRODUCT_ID." FROM ".ModelTag_to_product::TABLE." WHERE ".ModelTag_to_product::TABLE.DOT.ModelTag_to_product::F_TAG_ID."=".$tag.")";
		}
		if(count($params)){
			$params['where'] =implode(' AND ', $params);
			$product_info = $this->model()->load(false,$fields,$params);
			foreach ($product_info as &$item) {
				$item['shop'] = $this->model('shop')->getName($item[ModelProduct::F_SHOP_ID]);
				$item['tags'] = $this->model()->getAllTags($item[ModelProduct::F_PRODUCT_ID]);
				$item['image'] = import('helper.image',true)->get($item[ModelProduct::F_IMAGE_ID]);
			}
		}else{
			$product_info = $this->model()->loadOne($this->id,$fields,$params);
			$product_info['shop'] = $this->model('shop')->getName($product_info[ModelProduct::F_SHOP_ID]);
			$product_info['image'] = import('helper.image',true)->getForElement($this->name,$product_info[ModelProduct::F_PRODUCT_ID]);
			$product_info['tags'] = $this->model()->getAllTags($product_info[ModelProduct::F_PRODUCT_ID]);
			$product_info['params'] = $this->model('param')->getByCategoryId($product_info[ModelProduct::F_CATEGORY_ID]);
			$product_info['param_data'] = $this->model('param_data')->getByProductId($this->id);
		}
		$this->view->set('element',$product_info);
		$this->build();
	}
	/**
	 * Просмотр по конкретному магазину
	 * 
	 */
	public function showByShop(){
		parent::display(false);
		$view='info';
		$shop = Requestlocal::getString('shop',null);
		if($shop){
			$shop=$this->model('shop')->getId($shop);
		}
		if(!$shop && isset($_SESSION['shop_id'])) $shop = $_SESSION['shop_id'];
		if($shop){
			$this->showBySelector(ModelProduct::TABLE.DOT.ModelProduct::F_SHOP_ID.'="'.$shop.'"');
		} else {
			$this->product_info = false;
		}
		$this->view->set('info',$this->product_info);
		$this->build($view);
	}
	private function showBySelector($selector){
		import('model.category');
		$this->product_info=$this->model()->load(null,false,array(
			'fields' => array(ModelProduct::TABLE.DOT.'*', ModelCategory::TABLE.DOT.ModelCategory::F_TITLE.' AS category_name', '(SELECT COUNT(*) FROM comment WHERE comment.model_id = product.product_id AND comment.model="product") AS comments'),
			'where'=>$selector,
			'join'=>array(
				array('table'=>ModelCategory::TABLE, 'key'=>ModelCategory::F_CATEGORY_ID, 'join_table'=>ModelProduct::TABLE, 'join_field'=>ModelProduct::F_CATEGORY_ID)
		)
		));
		///надо чем то заменить
		foreach ($this->product_info as &$item) {
			$item['image'] = import('helper.image',true)->get($item[ModelProduct::F_IMAGE_ID]);
			$item['tags'] = $this->model()->getAllTags($item[ModelProduct::F_PRODUCT_ID]);
			$item['description'] = substr($item['description'],0,300);
		}
	}
	/**
	 * Форма редактирования
	 *
	 */
	public function edit(){
		parent::edit(true);
		Core::mustLogin();
		$this->view->set('element',$this->model()->loadOne($this->id,array(
		  ModelProduct::F_PRODUCT_ID,
		  ModelProduct::F_TITLE,
		  ModelProduct::F_DESCRIPTION,
		  ModelProduct::F_PRICE,
		  ModelProduct::F_PUBLISH,
		  ModelProduct::F_CATEGORY_ID
		  )));
		$this->build();
	}
	/**
	 * Форма создания
	 *
	 */
	public function add(){
		parent::add();
		Core::mustLogin();
		$this->build();
	}
	/**
	 * Создание
	 *
	 */
	public function save(){
		parent::save();
		if(!Core::mustLogin()) return false;
        $product_id = Requestlocal::getInt(ModelProduct::F_PRODUCT_ID,null,'post');
        $image_id = Requestlocal::getInt(ModelProduct::F_IMAGE_ID, 0);
        $shop_id = $this->model('shop')->getId(Requestlocal::getString('shop', ''));
        $category_id = Requestlocal::getInt(ModelProduct::F_CATEGORY_ID);
        if(!$shop_id) $shop_id = Vars::_(Router::SHOP_ID);
		if($shop_id && !$image_id) $image_id = '0';
		$result=$this->model()->save(
			array(
				ModelProduct::F_SORT  			=> 0,
				ModelProduct::F_PRICE  			=> Requestlocal::getInt(ModelProduct::F_PRICE),
				ModelProduct::F_CURRENCY_ID  	=> 1,
				ModelProduct::F_REAL_PRICE  	=> Requestlocal::getInt(ModelProduct::F_PRICE),
				ModelProduct::F_RAITING_SUM  	=> 0,
				ModelProduct::F_RAITING_COUNT  	=> 0,
			    ModelProduct::F_SHOP_ID  		=> $shop_id,
            	ModelProduct::F_USER_ID  		=> Core::user(),
            	ModelProduct::F_LANG_ID  		=> Core::lang(),
            	ModelProduct::F_CATEGORY_ID		=> $category_id,
            	ModelProduct::F_IMAGE_ID  		=> $image_id,
            	ModelProduct::F_DELETED			=> 0,
            	ModelProduct::F_CREATED			=> Core::date(),
            	ModelProduct::F_PUBLISH			=> Core::setAccess(),
            	ModelProduct::F_DESCRIPTION		=> Requestlocal::getString(ModelProduct::F_DESCRIPTION),
				ModelProduct::F_TITLE           => Requestlocal::getString(ModelProduct::F_TITLE),
			),
			$product_id
		);
		if(is_numeric($result)){
            $product_id = $result;
        }
        if(is_array($result)){
        	$this->view->result($result);
        } else {
        	if($product_id) {
	            //устанавливаем метки
	            import('helper.tag');
	            HelperTag::setTags('product', $product_id, Requestlocal::getString('tag_id','[]','post'));
	            //устранавливаем параметры
	            $paramList = $this->model('param')->getByCategoryId($category_id);
	            $delList = array();
	            foreach ($paramList as $item) $delList[] = $item[ModelParam::F_PARAM_ID];
	            //удаляем существующие параметры
	            $this->model('param_data')->delete(false, array(
	            	'where' => ModelParam_data::F_PRODUCT_ID . '=' . $product_id . ' AND ' . ModelParam_data::F_PARAM_ID . ' IN(' . implode(',',$delList) . ')'
	            ));
	            //получаем список пришедших параметров
	            $paramList = Requestlocal::getVar("param_",'post');
	            if(is_array($paramList)){
		            $addList = array();
		            foreach ($paramList as $key=>$item) {
		            	$tmp = array(
		            		ModelParam_data::F_PARAM_ID => $key,
		            		ModelParam_data::F_PRODUCT_ID => $product_id
		            	);
		            	$type = $this->model('param')->loadOne($key,ModelParam::F_TYPE);
		            	$tmp[$type==2 || $type==8 ? ModelParam_data::F_LONG_VALUE : ModelParam_data::F_SMALL_VALUE] = $item;
		            	$addList[] = $tmp;
		            }
		            $this->model('param_data')->saveList($addList);
		        }
	        }
	        //устанавливаем картинки
	        if(Requestlocal::getInt('newImage',0)){
	        	$list = Requestlocal::getString('images','');
	        	$list = explode(',', $list);
	        	$old = import('helper.image',true)->getForElement($this->name,$product_id);
	        	//устанавливаем новые картинки
	        	foreach ($list as $item) {
	        		$found = false;
	        		foreach ($old as $value) {
	        			if($value[ModelProduct::F_IMAGE_ID] == $item){
	        				$found = true;
	        				break;
	        			}
	        		}
	        		if(!$found){
	        			import('helper.image',true)->setModule($item,$this->name,$product_id);
	        		}
	        	}
	        	//удаляем старые картинки
	        	foreach ($old as $item) {
	        		$found = false;
	        		foreach ($list as $value) {
	        			if($value == $item[ModelProduct::F_IMAGE_ID]){
	        				$found = true;
	        				break;
	        			}
	        		}
	        		if(!$found){
	        			import('helper.image',true)->deleteImageById($item[ModelProduct::F_IMAGE_ID]);
	        		}
	        	}
	        }
        	$this->view->result(false);
        }
	}
	/**
	 * Удаление
	 *
	 */
	public function delete(){
		Core::mustLogin();
		parent::delete(true);
		if(parent::delete(true)){
			F('ControllerComment')->deleteComments('product',$this->id);
		}
		Core::redirect(base64_decode(Vars::_(Core::REFERER)),T::_('Deleted'));
	}
}